package fid

import (
	"time"

	"gitee.com/gaoguangting/fid/session"
	"github.com/labstack/echo"
)

type Controller struct {
	EchoContext echo.Context
	Session     session.Store
	SessionUser *SessionUser
	MethodName  string
	RequestMap  map[string]interface{}
}

func (this *Controller) StartRequest() APIError {
	return ErrNone
}

func (this *Controller) EndRequest() APIError {
	return ErrNone
}

func (this *Controller) SetUserWrapper(userWrap []byte) {
	var sessionUser *SessionUser
	if this.SessionUser != nil {
		sessionUser = this.SessionUser
	} else {
		sessionUser = &SessionUser{}
	}
	sessionUser.LastAccessTime = time.Now()
	sessionUser.UserWrapper = userWrap
	this.Session.Set(SESSION_KEY_USER, *sessionUser)
}

func (this *Controller) ClearUserWrapper() {
	this.Session.Delete(SESSION_KEY_USER)
}

func (this *Controller) SetPrivileges(privileges ...string) {
	if this.SessionUser == nil {
		return
	} else {
		sessionUser := this.SessionUser
		sessionUser.LastAccessTime = time.Now()
		sessionUser.Privileges = privileges
		this.Session.Set(SESSION_KEY_USER, *sessionUser)
	}
}

// 必须包含所有的权限
func (this *Controller) MustPrivilegeAll(privileges ...string) {
	pass := true
	unPassPrivilege := ""
	if this.SessionUser != nil {
		for _, p := range privileges {
			thisHas := false
			for _, hasP := range this.SessionUser.Privileges {
				if p == hasP {
					thisHas = true
					break
				}
			}
			if !thisHas {
				pass = false
				unPassPrivilege = p
				break
			}
		}
	} else {
		pass = false
	}
	if !pass {
		panic(FrameworkError{
			PanicError: PanicErrorAuth,
			Params:     []string{unPassPrivilege},
		})
	}
}

// 包含其中一个权限即可
func (this *Controller) MustPrivilegeIn(privileges ...string) {
	pass := false
	if this.SessionUser != nil {
		for _, p := range privileges {
			thisHas := false
			for _, hasP := range this.SessionUser.Privileges {
				if p == hasP {
					thisHas = true
					break
				}
			}
			if thisHas {
				pass = true
				break
			}
		}
	} else {
		pass = false
	}
	if !pass {
		panic(FrameworkError{
			PanicError: PanicErrorAuth,
			Params:     privileges,
		})
	}
}

func (f *Fid) InstallController(controller interface{}) {
	proto := newProto(controller)
	if f.protos == nil {
		f.protos = make([]*ControllerProto, 0)
	}
	proto.sessionManager = f.sessionManager
	proto.fid = f
	proto.installRouter()
	f.protos = append(f.protos, proto)
}
